package com.sj.command;

import com.sj.common.lang.Const;
import com.sj.pojo.MsgTypeEnum;
import com.sj.pojo.Protocol;
import com.sj.utils.TransferUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-07-12
 * Time: 上午 10:55
 * Description: Map命令
 * 用来编写map命令的处理逻辑
 *
 * @author xiaoqi
 * @since 2022-07-12
 */
public class CommandMap extends Command {

    private CommandMap() {

    }

    public static Protocol doing(String msg) {
        return doMap(msg);
    }

    private static Protocol doMap(String msg) {
        String[] instruct = msg.split(" ");
        if (Const.H_SET.equalsIgnoreCase(instruct[0])) {
            if (instruct.length < 4) {
                return protocol.getProtocol(MsgTypeEnum.RESPONSE, "错误的命令!");
            }
            HashMap<String, String> innerMap = new HashMap<>();
            innerMap = (HashMap<String, String>) map.getOrDefault(instruct[1], innerMap);
            innerMap.put(instruct[2], TransferUtils.joint(instruct, 3));
            map.put(instruct[1], innerMap);
            return protocol.getProtocol(MsgTypeEnum.RESPONSE, "Ok, current map size: " + innerMap.size());
        } else if (Const.H_GET.equalsIgnoreCase(instruct[0])) {
            Protocol check = TransferUtils.check(instruct, 3);
            if (check != null) {
                return check;
            }
            Map<String, String> innerMap = map.get(instruct[1]);
            if (innerMap == null) {
                return protocol.getProtocol(MsgTypeEnum.RESPONSE, "Error, parent key '" + instruct[1] + "' is undefine!");
            }
            String res = innerMap.get(instruct[2]);
            if (res == null) {
                return protocol.getProtocol(MsgTypeEnum.RESPONSE, "Error, '" + instruct[2] + "' is undefine!");
            }
            return protocol.getProtocol(MsgTypeEnum.RESPONSE, res);
        }
        return protocol.getProtocol(MsgTypeEnum.RESPONSE, "do nothing!");
    }
}